package models

import (
	"cloudops/src/common"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

// 任务结构体
type JobTask struct {
	Model // 不用每次写ID 和 createAt了

	Title string `json:"title" gorm:"type:varchar(100);uniqueIndex;comment:名称"`

	Account            string `json:"account" gorm:"comment:执行的账号"`
	Args               string `json:"args" gorm:"comment:参数"`
	ScriptContent      string `json:"scriptContent" gorm:"comment:脚本内容 来源2种： 01 当场写的 02 从script表中 获取"`
	ExecTimeoutSeconds int    `json:"execTimeoutSeconds"  gorm:"comment:执行超时时间"`

	BatchSize       int    `json:"batchSize"  gorm:"comment:机器并发数量"`
	OnErrorStrategy string `json:"onErrorStrategy"  gorm:"comment:遇到某些机器出错后的策略 ：有忽略的执行完 遇到错误就停止的 遇到错误就暂停的"`

	TreeNodeId     uint   `json:"treeNodeId" gorm:"comment:关联的服务树节点"`
	NodePath       string `json:"nodePath" ` // a.b.c.d
	HostsRaw       string `json:"hostsRaw" gorm:"type:text;comment:机器的ip列表"`
	ScheduledHosts string `json:"scheduledHosts" gorm:"type:text;comment:已经下发的机器的ip列表 ，目的就是用来并发 或者 暂停"`
	Status         string `json:"status"  gorm:"comment:当前状态"`
	Action         string `json:"action"  gorm:"comment:动作"`
	HostsIdsRaw    string `json:"hostsIdsRaw" gorm:"-"`
	ActualFlowData string `json:"actualFlowData" gorm:"type:text;comment:任务执行的状态记录"`
	UserID         uint
	TotalNum       int `json:"totalNum"`

	TimeLineItems  []WorkOrderTimeLineItem `json:"timeLineItems" gorm:"-"`
	Key            string                  `json:"key" gorm:"-"` //给前端表格
	CreateUserName string                  `json:"createUserName" gorm:"-"`
	Value          uint                    `json:"key"  gorm:"-"`
}

// 根据ID获取任务
func GetJobTaskById(id int) (*JobTask, error) {
	var dbJobTask JobTask
	err := DB.Where("id = ?", id).First(&dbJobTask).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("菜单不存在")
		}
		return nil, fmt.Errorf("查询失败:%w", err)
	}
	return &dbJobTask, err
}

// 更新任务
func (obj *JobTask) JobTaskUpdateOne() error {
	return DB.Updates(obj).Error
}

// 创建任务
func (obj *JobTask) JobTaskCreate() error {
	return DB.Create(obj).Error
}

// 获取未执行的任务
func GetJobTaskUnDone(statusArr []string) (JobTasks []*JobTask, err error) {
	err = DB.Where("status in ?", statusArr).Find(&JobTasks).Error
	return
}

// 更新timeline
func (obj *JobTask) UpdateFlowData(action string, userName string) error {
	outPut := fmt.Sprintf("%v任务",
		common.JOB_ACTION_TRAN_MAP[action],
	)

	user, err := GetUserByUserName(userName)
	if err != nil {
		return err
	}

	oneFlow := WorkOrderTimeLineItem{

		TimeAndNodeName: fmt.Sprintf("%v %v",
			time.Now().Format("2006-01-02 15:04:05"),
			outPut,
		),
		//DefineUserOrGroup: userName,
		DefineUserOrGroup: user.RealName,
		ActualUser:        user.RealName,
		OutPut:            outPut,
		Color:             "green",
	}
	var flows []WorkOrderTimeLineItem
	if obj.ActualFlowData != "" {
		err := json.Unmarshal([]byte(obj.ActualFlowData), &flows)
		if err != nil {
			return err
		}
	}

	flows = append(flows, oneFlow)
	flowsData, _ := json.Marshal(flows)
	obj.ActualFlowData = string(flowsData)
	return nil
}

// 获取所有任务
func GetJobTaskAll() (JobTasks []*JobTask, err error) {
	err = DB.Find(&JobTasks).Error
	return
}

// 获取任务列表 做分页限制展示
func GetJobTaskByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*JobTask, err error) {
	err = DB.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

// 填充前端数据
func (obj *JobTask) FillFrontAllData() {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.RealName
	}

	// 处理时间轴
	var actialFlowData []WorkOrderTimeLineItem
	_ = json.Unmarshal([]byte(obj.ActualFlowData), &actialFlowData)
	timeLineItems := []WorkOrderTimeLineItem{
		{
			TimeAndNodeName: fmt.Sprintf("%v 任务创建",
				obj.CreatedAt.Format("2006-01-02 15:04:05"),
			),
			DefineUserOrGroup: fmt.Sprintf("%v", obj.CreateUserName),
			Color:             "green",
			OutPut:            "任务创建",
		},
	}

	if len(actialFlowData) > 0 {
		timeLineItems = append(timeLineItems, actialFlowData...)
	}

	obj.TimeLineItems = timeLineItems
}
